﻿//bibaoke.com

using Less.Text;

namespace Less.SqlParser
{
    internal class FromCommaReader : ReaderBase
    {
        internal override ReaderBase Read()
        {
            Word word = this.ReadWord();

            Select select = this.CastToSelect();

            if (word.Separator.IsEmpty())
            {
                if (select.IsNotNull())
                {
                    if (select.From.Tables.Count == 0)
                    {
                        throw new ParseException(this.LastWord);
                    }
                }

                return this.Pass<EndReader>();
            }

            if (word.Separator == ",")
            {
                if (select.IsNotNull())
                {
                    if (word.Content.IsNotEmpty())
                    {
                        select.From.AddTable(word);
                    }

                    return this.Pass<FromReader>();
                }
            }
            else if (word.Separator.IsWhiteSpace())
            {
                if (word.Content.CompareIgnoreCase("where"))
                {
                    if (select.IsNotNull())
                    {
                        select.CurrentClause.End = this.LastWord.WordEnd;

                        select.Where = new Where(word.Begin);

                        select.CurrentClause = select.Where;

                        return this.Pass<WhereReader>();
                    }
                }
                else if (word.Content.CompareIgnoreCase("order"))
                {
                    if (select.IsNotNull())
                    {
                        select.CurrentClause.End = this.LastWord.WordEnd;

                        select.OrderBy = new OrderBy(word.Begin);

                        select.CurrentClause = select.OrderBy;

                        return this.Pass<OrderByReader>();
                    }
                }
                else if (word.Content.CompareIgnoreCase("limit"))
                {
                    if (word.Separator.IsWhiteSpace())
                    {
                        select.CurrentClause.End = this.LastWord.WordEnd;

                        select.Limit = new Limit(word.Begin);

                        select.CurrentClause = select.Limit;

                        return this.Pass<LimitReader>();
                    }
                    else
                    {
                        throw new ParseException(word);
                    }
                }
            }
            else
            {
                throw new ParseException(word);
            }

            return this.Pass<EndReader>();
        }
    }
}
